package com.itealabs.postjson.ext;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

import com.itealabs.postjson.JsonCallWaiter;
import com.itealabs.postjson.JsonCallWaiterLocator;

/**
 * @version $Id: JsonCallFilter.java 29 2010-09-01 09:45:14Z iteahere $
 * @author itea
 * 2010-9-1
 */
public class JsonCallFilter implements JsonCallWaiterLocator {

	private Set<String> denys = new HashSet<String>();
	private List<Pattern> denyRegex = new ArrayList<Pattern>();
	private JsonCallWaiterLocator chain;
	
	public JsonCallWaiter getCallWaiter(String method) {
		if(isEmpty(method) || denys.contains(method) || inDenyRegex(method)) return null;
		return chain.getCallWaiter(method);
	}
	
	private boolean inDenyRegex(String s) {
		for(Pattern r : denyRegex)
			if(r.matcher(s).matches()) return true;
		return false;
	}

	public void setDenys(List<String> denyExpr) {
		for(String e : denyExpr) {
			if(isEmpty(e)) continue;
			if(e.startsWith("regex:")) denyRegex.add(Pattern.compile(e.substring(6)));
			else denys.add(e);
		}
	}
	
	private static boolean isEmpty(String s) {
		return s == null || s.trim().length() == 0;
	}

	public void setChain(JsonCallWaiterLocator chain) {
		this.chain = chain;
	}
}
